package com.itboye.mengwu.buy.ui;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Observable;
import java.util.Observer;
import java.util.Random;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract.CommonDataKinds.Relation;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.itboye.core.alert.ByAlert;
import com.itboye.core.object.BaseActivity;
import com.itboye.core.object.ResultEntity;
import com.itboye.core.object.SpPublicParams;
import com.itboye.core.utils.ParseDouble;
import com.itboye.core.utils.SPUtils;
import com.itboye.mengwu.R;
import com.itboye.mengwu.alipay.PayResult;
import com.itboye.mengwu.alipay.SignUtils;
import com.itboye.mengwu.app.ui.main.MainPresenter;
import com.itboye.mengwu.app.ui.mymeng.MyOrderActivity;
import com.itboye.mengwu.data.model.AppConfigModel;
import com.itboye.mengwu.data.model.BuyBean;
import com.itboye.mengwu.data.model.OrderBean;
import com.itboye.mengwu.data.model.VIPPersonalBean;
import com.itboye.mengwu.data.model.WeChatBean;
import com.itboye.mengwu.data.presenter.ConfigAppPresenter;
import com.itboye.mengwu.data.repository.WxPayRepository;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

public class PayTypeActivity extends BaseActivity implements Observer {

	private List<String> data;
	ImageView back;
	TextView txt_title;
	MainPresenter mainPresenter;
	private IWXAPI api;
	TextView txt_yue, txt_zhifubao, txt_wx, txt_yue_yue, money, heji, pay_time;
	private AppConfigModel appConfigModel;
	ImageView yue_selectBtn, zhifubao_selectBtn, wx_selectBtn;
	private ConfigAppPresenter appPresenter;
	boolean isYe = true, isZFB, isWX;
	RelativeLayout goPay;
	String totalPrice, orderCode;
	LinearLayout testzhifu;
	OrderBean orderBean = new OrderBean();
	protected String desc;
	private TextView txt_gopay;
	protected String uid;
	protected int payType;
	private String myyue;
	private String shouldPay;
	private String type;

	@Override
	public int initView() {
		// TODO Auto-generated method stub
		return R.layout.activity_pay_type;
	}

	@Override
	public void onMyCreate() {
		IntentFilter filter = new IntentFilter("close");
		registerReceiver(receiver, filter);
		mainPresenter = new MainPresenter(this);
		appPresenter = new ConfigAppPresenter(PayTypeActivity.this);
		uid = SPUtils.get(this, null, SpPublicParams.UID, "") + "";
		appPresenter.getGuanZhu(uid, "");
		type = getIntent().getStringExtra("type");// 支付类型
		if (type != null) {
			if (type.equals("aliy")) {// 支付宝
				pay((BuyBean) getIntent().getSerializableExtra("model"));
			} else if (type.equals("wx")) {// 微信
				wxPay((BuyBean) getIntent().getSerializableExtra("model"));
			}
			return;
		}
		orderBean = (OrderBean) getIntent().getSerializableExtra("model");
		// myyue = (SPUtils.get(this, null, SpPublicParams.COIN, "") + "");

		// ////////从Web跳转过来start

		// ///////从Web跳转过来end
		if (orderBean != null) {
			totalPrice = orderBean.getTotalPrice();
			orderCode = orderBean.getCode() == null ? orderBean.getOrderCode()
					: orderBean.getCode();
		}

		else {
			totalPrice = getIntent().getStringExtra("price");
			orderCode = getIntent().getStringExtra("orderCode");
		}
		money.setText(ParseDouble.getDouble(Double.parseDouble(totalPrice))
				+ "");
		txt_gopay.setText("去支付(共￥"
				+ ParseDouble.getDouble(Double.parseDouble(totalPrice)) + "元)");

		// testzhifu.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// // TODO Auto-generated method stub
		// mainPresenter.testPay("153", orderBean.getCode());
		// }
		// });

		// yue_selectBtn.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// // TODO Auto-generated method stub
		// if (isYe) {
		// yue_selectBtn.setSelected(false);
		// } else {
		// yue_selectBtn.setSelected(true);
		// }
		// isYe = !isYe;
		// }
		// });
		zhifubao_selectBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				isZFB = true;
				isWX = false;
				wx_selectBtn.setBackgroundResource(R.drawable.zhifu_unselected);
				zhifubao_selectBtn
						.setBackgroundResource(R.drawable.zhifu_selected);
				if (Double.parseDouble(yu_e) >= Double.parseDouble(totalPrice)) {
					yue_selectBtn
							.setBackgroundResource(R.drawable.zhifu_unselected);
					isYe = false;
				} else {
					isYe = true;
					yue_selectBtn
							.setBackgroundResource(R.drawable.zhifu_selected);
				}
			}
		});
		wx_selectBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				isWX = true;
				isZFB = false;
				wx_selectBtn.setBackgroundResource(R.drawable.zhifu_selected);
				zhifubao_selectBtn
						.setBackgroundResource(R.drawable.zhifu_unselected);
				if (Double.parseDouble(yu_e) >= Double.parseDouble(totalPrice)) {
					isYe = false;
					yue_selectBtn
							.setBackgroundResource(R.drawable.zhifu_unselected);
				} else {
					isYe = true;
					yue_selectBtn
							.setBackgroundResource(R.drawable.zhifu_selected);
				}
			}
		});
		goPay.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (isWX && (!isZFB)) {
					payType = 2;
				} else if (isZFB && (!isWX)) {
					payType = 1;
				}
				if (isYe && (!isWX) && (!isZFB)) {
					payType = 3;
				}
				if (!isYe) {
					shouldPay = "0";
				}

//				if (!orderCode.contains(";")) {
//					orderCode += ";";
//				}
				System.out.println("uid:" + uid + "orderCode:" + orderCode
						+ "paytype" + payType + "shouldPay" + shouldPay);
				mainPresenter.payNow(uid, orderCode, payType + "", shouldPay);
			}
		});
		appConfigModel = new AppConfigModel();
		appPresenter.getInfo(appConfigModel);
		api = WXAPIFactory.createWXAPI(this, SpPublicParams.APP_ID);
		api.registerApp(SpPublicParams.APP_ID);
		txt_title.setText("支付");
		heji.setText(totalPrice);
		back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});

	}

	BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			finish();
		}
	};

	public void refresh() {
		Intent intent = new Intent("refresh");
		sendBroadcast(intent);
	}

	// 商户PID
	public static final String PARTNER = "2088221673470288";
	// 商户收款账号
	public static final String SELLER = "mengwukids@163.com";
	// 商户私钥，pkcs8格式
	// public static final String RSA_PRIVATE =
	// "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAKdURORLBGPAZKLBT42KvmWmplG6aLo2alJ8Yv4tAfN8RT52Uiv1KV0KTkb7gP/8jshdPoQdSCJltcnrYEJqnfprQjTmHFwqLJTnkp7ZoVm2bTfVNdfDsCFOM/jCUYpTROuUpqjlTcwVZDiJ4J3FTFZn8i4HB01MwmoCh0pPmM0vAgMBAAECgYAEXv8tt4f10yDN357kY6t1nFTb7bKuqp08amNroGFcqvJkH1MmMtFRzOMel5NXHJHeShFIAjvQKjgFflCVa5OU3EdEuh03LjLnN65zLK0l/GYXIcqcNGXQ6hkSvEyvrZkj3kxU7xPCynJYS5Dgp43N479cfkTt1dwnW/IARsaRAQJBANR2GRg+xAqcExJmS7YStD/YqarkVAAea85rxQhdWmQlDId8+lWslSxGqWkrco3h0rzLBGM2x0FntvfIIJ3kRkkCQQDJnoAVWc/WR+vp27+H/rJkBt5VH5JEdpjNPejBN8eEiOxLVqgR6xp35h791zq0DsjR2CxjAPThMAy/LciuShe3AkAC55pwOmtzua6JEdz3IEpWlR+8tmJvnfrbV53Z/2y88cS6FXtWsIVZlZ27Uly+k9fNvPjSYm1W95QIzzOi9PwBAkAKy47GFeH38i/ifJ6btHpuuqNq4V7ehY8W5iqxNcBcC0zDl+c11mW7Z7nfE4gUHfqIqc9umZ2C9SSpk9T76AGvAkAtEkrt8HuItXLCagyuEnstWd4rkR1UiYDUsvK4FOc11nm495rcfpHkl8rtRa17y+sIPpf9VDdWzGgwFboE0n2T";
	// public static final String
	// RSA_PRIVATE="MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAKdURORLBGPAZKLBT42KvmWmplG6aLo2alJ8Yv4tAfN8RT52Uiv1KV0KTkb7gP/8jshdPoQdSCJltcnrYEJqnfprQjTmHFwqLJTnkp7ZoVm2bTfVNdfDsCFOM/jCUYpTROuUpqjlTcwVZDiJ4J3FTFZn8i4HB01MwmoCh0pPmM0vAgMBAAECgYAEXv8tt4f10yDN357kY6t1nFTb7bKuqp08amNroGFcqvJkH1MmMtFRzOMel5NXHJHeShFIAjvQKjgFflCVa5OU3EdEuh03LjLnN65zLK0l/GYXIcqcNGXQ6hkSvEyvrZkj3kxU7xPCynJYS5Dgp43N479cfkTt1dwnW/IARsaRAQJBANR2GRg+xAqcExJmS7YStD/YqarkVAAea85rxQhdWmQlDId8+lWslSxGqWkrco3h0rzLBGM2x0FntvfIIJ3kRkkCQQDJnoAVWc/WR+vp27+H/rJkBt5VH5JEdpjNPejBN8eEiOxLVqgR6xp35h791zq0DsjR2CxjAPThMAy/LciuShe3AkAC55pwOmtzua6JEdz3IEpWlR+8tmJvnfrbV53Z/2y88cS6FXtWsIVZlZ27Uly+k9fNvPjSYm1W95QIzzOi9PwBAkAKy47GFeH38i/ifJ6btHpuuqNq4V7ehY8W5iqxNcBcC0zDl+c11mW7Z7nfE4gUHfqIqc9umZ2C9SSpk9T76AGvAkAtEkrt8HuItXLCagyuEnstWd4rkR1UiYDUsvK4FOc11nm495rcfpHkl8rtRa17y+sIPpf9VDdWzGgwFboE0n2T";
	public static final String RSA_PRIVATE = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALR34U2zZpxNFEENdP69E6Ae6L9vKTBcbza7Eag+v/9FuMNIhUPmDlmUBhc6EwDzxkNKET4DNaHHTDJuxnjQQZ1TvvLDHTNbzGP/wVA9sZS7w09NC3bM8OcyAFvFzPIZhSlQgUythL9H8NQB55qJhjwlZuFIPyk3sm8B3xT7BfdLAgMBAAECgYBWT7+B2fuJZZP6SOVbsDJismW+qPuaFZtbIb0gKmLJRB9JxrV18+GJFjKTiULtgamhJRt5/S75YMgglrp1raSzPG3KRPsFvhO/LVPE/CuLYhrULmiqV0a5b1tgm64g5++Xl4i29DMZENqmJDXziWEpF+ZnEEaJB0ywy+Dak50RAQJBANkq5UZ9lA3xYvoJGE+pehgmMJ/pnYtnE8/udFm5gWQhcKjg06JjUdKUSlVB27Kg/BpGtXXwcDvew+GXh7lMqLkCQQDUvQf5xU0IYzGgSegV4mgmokuvYSgOTbUlhrsx7yOwa29qmOfiaEcjIlQa+Oy2lFb4DPhHi83o9lzo/SSL4xYjAkEAuXgUFe68GmhUkpxf4fEo8CT1lC0tutfOqN/LCLIQmpago+pXdLGEOOci0MuNOXKZvEs1QMOW5trqyejjJlMdKQJAIL8YQzJDsU7TjMDToMrBDXFeBRkHeWwsviIHHqCY9ccT12zCBO/YQ2g9WgmHJnOfD3+vmBPFFl8V3idZQM8r0QJAV7BRic79/X3StEm/afjXlqjZ2ONo5Cfib+kRdXmvriJfP7/aHO1tE1nLMdDWCJlzIQQGxedVrhdJMq6qpNT2MA==";
	// 支付宝公钥
	public static final String RSA_PUBLIC = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCnxj/9qwVfgoUh/y2W89L6BkRAFljhNhgPdyPuBV64bfQNN1PjbCzkIM6qRdKBoLPXmKKMiFYnkd6rAoprih3/PrQEB/VsW8OoM8fxn67UDYuyBTqA23MML9q1+ilIZwBC2AQ2UBVOrFXfFl75p6/B5KsiNG9zpgmLCUYuLkxpLQIDAQAB";
	private static final int SDK_PAY_FLAG = 1;

	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {
		@SuppressWarnings("unused")
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SDK_PAY_FLAG: {
				PayResult payResult = new PayResult((String) msg.obj);
				/**
				 * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
				 * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
				 * docType=1) 建议商户依赖异步通知
				 */
				String resultInfo = payResult.getResult();// 同步返回需要验证的信息

				String resultStatus = payResult.getResultStatus();
				// 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
				if (TextUtils.equals(resultStatus, "9000")) {
					Toast.makeText(PayTypeActivity.this, "支付成功",
							Toast.LENGTH_SHORT).show();
					showProgressDialog("更新余额中", true);
					refresh();
					appPresenter.getGuanZhu(uid, "");
					finish();
				} else {
					// 判断resultStatus 为非"9000"则代表可能支付失败
					// "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
					if (TextUtils.equals(resultStatus, "8000")) {
						Toast.makeText(PayTypeActivity.this, "支付结果确认中",
								Toast.LENGTH_SHORT).show();

					} else {
						// 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
						Toast.makeText(PayTypeActivity.this, "支付失败",
								Toast.LENGTH_SHORT).show();
					}
					refresh();
					finish();
				}
				break;
			}
			default:
				break;
			}
		};
	};
	private VIPPersonalBean vipPersonalBean;
	private String yu_e;

	/**
	 * call alipay sdk pay. 调用SDK支付
	 * 
	 */
	public void pay(BuyBean orderBean) {
		String innerOrderCode = "";
		String innerTotalPrice = "";
		String innerDesc = "";
		if (TextUtils.isEmpty(PARTNER) || TextUtils.isEmpty(RSA_PRIVATE)
				|| TextUtils.isEmpty(SELLER)) {
			new AlertDialog.Builder(this)
					.setTitle("警告")
					.setMessage("需要配置PARTNER | RSA_PRIVATE| SELLER")
					.setPositiveButton("确定",
							new DialogInterface.OnClickListener() {
								public void onClick(
										DialogInterface dialoginterface, int i) {
									//
									finish();
								}
							}).show();
			return;
		}
		try {
			if (orderBean != null) {
				innerOrderCode = orderBean.getPayInfo().getCode();
				innerDesc = orderBean.getPayInfo().getDesc();
				innerTotalPrice = orderBean.getPayInfo().getTotalPrice();
				if (isYe) {// 使用余额
					// totalPrice = Double.parseDouble(totalPrice)
					// - Double.parseDouble(txt_yue_yue.getTag().toString())
					// + "";
					if (Double.parseDouble(totalPrice) <= 0) {
						innerTotalPrice = "0.01";
					}
				}
			} else {
				innerDesc = getIntent().getStringExtra("desc");
			}
		} catch (Exception e) {
			// TODO: handle exception
			innerOrderCode = orderBean.getPayInfo().getCode();
			innerDesc = orderBean.getPayInfo().getDesc();
			innerTotalPrice = orderBean.getPayInfo().getTotalPrice();
			System.out.println("请输入innerOrderCode" + innerOrderCode
					+ "innerDesc:" + innerDesc + "innerTotalPrice"
					+ innerTotalPrice);
		}

		String orderInfo = getOrderInfo(innerOrderCode, innerDesc,
				innerTotalPrice);

		/**
		 * 特别注意，这里的签名逻辑需要放在服务端，切勿将私钥泄露在代码中！
		 */
		String sign = sign(orderInfo);
		try {
			/**
			 * 仅需对sign 做URL编码
			 */
			sign = URLEncoder.encode(sign, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		/**
		 * 完整的符合支付宝参数规范的订单信息
		 */
		final String payInfo = orderInfo + "&sign=\"" + sign + "\"&"
				+ getSignType();

		Runnable payRunnable = new Runnable() {

			@Override
			public void run() {
				// 构造PayTask 对象
				PayTask alipay = new PayTask(PayTypeActivity.this);
				// 调用支付接口，获取支付结果
				String result = alipay.pay(payInfo, true);

				Message msg = new Message();
				msg.what = SDK_PAY_FLAG;
				msg.obj = result;
				mHandler.sendMessage(msg);
			}
		};

		// 必须异步调用
		Thread payThread = new Thread(payRunnable);
		payThread.start();
	}

	/**
	 * get the sdk version. 获取SDK版本号
	 * 
	 */
	public void getSDKVersion() {
		PayTask payTask = new PayTask(this);
		String version = payTask.getVersion();
		Toast.makeText(this, version, Toast.LENGTH_SHORT).show();
	}

	/**
	 * 原生的H5（手机网页版支付切natvie支付） 【对应页面网页支付按钮】
	 * 
	 * @param v
	 */
	// public void h5Pay(View v) {
	// Intent intent = new Intent(this, H5PayDemoActivity.class);
	// Bundle extras = new Bundle();
	// /**
	// * url是测试的网站，在app内部打开页面是基于webview打开的，demo中的webview是H5PayDemoActivity，
	// * demo中拦截url进行支付的逻辑是在H5PayDemoActivity中shouldOverrideUrlLoading方法实现，
	// * 商户可以根据自己的需求来实现
	// */
	// String url = "http://m.meituan.com";
	// // url可以是一号店或者美团等第三方的购物wap站点，在该网站的支付过程中，支付宝sdk完成拦截支付
	// extras.putString("url", url);
	// intent.putExtras(extras);
	// startActivity(intent);
	//
	// }

	/**
	 * create the order info. 创建订单信息
	 * 
	 */
	private String getOrderInfo(String subject, String body, String price) {

		// 签约合作者身份ID
		String orderInfo = "partner=" + "\"" + PARTNER + "\"";

		// 签约卖家支付宝账号
		orderInfo += "&seller_id=" + "\"" + SELLER + "\"";

		// 商户网站唯一订单号
		orderInfo += "&out_trade_no=" + "\"" + getOutTradeNo() + "\"";

		// 商品名称
		orderInfo += "&subject=" + "\"" + subject + "\"";

		// 商品详情
		orderInfo += "&body=" + "\"" + body + "\"";

		// 商品金额
		orderInfo += "&total_fee=" + "\"" + price + "\"";

		// 服务器异步通知页面路径
		orderInfo += "&notify_url=" + "\"" + "http://notify.msp.hk/notify.htm"
				+ "\"";

		// 服务接口名称， 固定值
		orderInfo += "&service=\"mobile.securitypay.pay\"";

		// 支付类型， 固定值
		orderInfo += "&payment_type=\"1\"";

		// 参数编码， 固定值
		orderInfo += "&_input_charset=\"utf-8\"";

		// 设置未付款交易的超时时间
		// 默认30分钟，一旦超时，该笔交易就会自动被关闭。
		// 取值范围：1m～15d。
		// m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
		// 该参数数值不接受小数点，如1.5h，可转换为90m。
		orderInfo += "&it_b_pay=\"30m\"";

		// extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
		// orderInfo += "&extern_token=" + "\"" + extern_token + "\"";

		// 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
		orderInfo += "&return_url=\"m.alipay.com\"";

		// 调用银行卡支付，需配置此参数，参与签名， 固定值 （需要签约《无线银行卡快捷支付》才能使用）
		// orderInfo += "&paymethod=\"expressGateway\"";

		return orderInfo;
	}

	/**
	 * get the out_trade_no for an order. 生成商户订单号，该值在商户端应保持唯一（可自定义格式规范）
	 * 
	 */
	private String getOutTradeNo() {
		SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss",
				Locale.getDefault());
		Date date = new Date();
		String key = format.format(date);

		Random r = new Random();
		key = key + r.nextInt();
		key = key.substring(0, 15);
		return key;
	}

	/**
	 * sign the order info. 对订单信息进行签名
	 * 
	 * @param content
	 *            待签名订单信息
	 */
	private String sign(String content) {
		return SignUtils.sign(content, RSA_PRIVATE);
	}

	/**
	 * get the sign type we use. 获取签名方式
	 * 
	 */
	private String getSignType() {
		return "sign_type=\"RSA\"";
	}

	@Override
	public void update(Observable observable, Object data) {
		// TODO Auto-generated method stub
		ResultEntity entity = handlerError(data);
		if (entity != null) {
			if (entity.getEventType() == MainPresenter.WxPaySuccess) {
				WeChatBean bean = (WeChatBean) entity.getData();
				PayReq req = new PayReq();

				req.appId = bean.getAppid();
				req.partnerId = bean.getPartnerid();
				req.prepayId = bean.getPrepayid();
				req.nonceStr = bean.getNoncestr();
				req.timeStamp = bean.getTimestamp();
				req.packageValue = "Sign=WXPay";
				req.sign = bean.getSign();
				boolean is = api.sendReq(req);
				if (is) {
					// ByAlert.alert("已调其成功");
					Log.v("wxpay", is + "");
					finish();
				} else {
					Toast.makeText(PayTypeActivity.this, "调起微信支付失败", 0).show();
				}
			} else if (entity.getEventType() == MainPresenter.WxPayFail) {
				ByAlert.alert("失败");
			} else if (entity.getEventType() == ConfigAppPresenter.ConfigApp_success) {
				appConfigModel = (AppConfigModel) entity.getData();
				txt_yue.setText(appConfigModel.getAndroidPayType().get(2));
				txt_zhifubao.setText(appConfigModel.getAndroidPayType().get(0));
				txt_wx.setText(appConfigModel.getAndroidPayType().get(1));
			} else if (entity.getEventType() == MainPresenter.testFail) {
				//ByAlert.alert(entity.getData() + "");
			} else if (entity.getEventType() == MainPresenter.testSuccess) {
				//ByAlert.alert(entity.getData() + "");
				finish();
			} else if (entity.getEventType() == MainPresenter.PayNowSuccess) {
				BuyBean bean = (BuyBean) entity.getData();
				if (bean != null) {
					if (payType == 3) {
						//ByAlert.alert(bean.getPayMsg());
						SPUtils.put(PayTypeActivity.this, null,
								SpPublicParams.COIN, Double.parseDouble(myyue)
										- Double.parseDouble(shouldPay));
						Intent intent = new Intent(PayTypeActivity.this,
								MyOrderActivity.class);
						intent.putExtra("index", 1);
						startActivity(intent);
						finish();
						appPresenter.getGuanZhu(uid, "");
					} else {
						SPUtils.put(PayTypeActivity.this, null,
								SpPublicParams.COIN, "0");
						if (isZFB) {
							pay(bean);
						} else {
							wxPay(bean);
						}
					}
				} else {
					ByAlert.alert("余额支付失败");
				}
			} else if (entity.getEventType() == MainPresenter.PayNowFail) {
				finish();
			} else if (entity.getEventType() == ConfigAppPresenter.Guanzhu_success) {
				vipPersonalBean = (VIPPersonalBean) entity.getData();
				yu_e = vipPersonalBean.getBalance();
				myyue = vipPersonalBean.getBalance();
				SPUtils.put(this, null, SpPublicParams.COIN, yu_e);
				txt_yue_yue.setText("可用余额： ￥"
						+ SPUtils.get(this, null, SpPublicParams.COIN, ""));
				if (Double.parseDouble(yu_e) >= Double.parseDouble(totalPrice)) {// 余额充足
					shouldPay = totalPrice;
				} else {// 不足
					shouldPay = yu_e;
				}
				if (Double.parseDouble(totalPrice) <= Double
						.parseDouble(SPUtils.get(this, null,
								SpPublicParams.COIN, "") + "")) {
					yue_selectBtn.setEnabled(true);
					yue_selectBtn.setSelected(true);
					zhifubao_selectBtn.setEnabled(false);
					wx_selectBtn.setEnabled(false);
					yue_selectBtn.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							if (isYe) {// 不用余额
								yue_selectBtn.setSelected(false);
								yue_selectBtn
										.setBackgroundResource(R.drawable.zhifu_unselected);
								if (!wx_selectBtn.isSelected()
										&& !zhifubao_selectBtn.isSelected()) {
									zhifubao_selectBtn.setSelected(true);
									wx_selectBtn.setSelected(false);
									isZFB = true;
									isWX = false;
									zhifubao_selectBtn
											.setBackgroundResource(R.drawable.zhifu_selected);
									wx_selectBtn
											.setBackgroundResource(R.drawable.zhifu_unselected);
								}

								wx_selectBtn.setEnabled(true);
								zhifubao_selectBtn.setEnabled(true);
							} else {// 使用余额
								yue_selectBtn.setSelected(true);
								wx_selectBtn.setSelected(false);
								yue_selectBtn
										.setBackgroundResource(R.drawable.zhifu_selected);
								zhifubao_selectBtn.setSelected(false);
								zhifubao_selectBtn
										.setBackgroundResource(R.drawable.zhifu_unselected);
								wx_selectBtn
										.setBackgroundResource(R.drawable.zhifu_unselected);
								isZFB = false;
								isWX = false;
							}
							isYe = !isYe;
						}
					});

				} else {
					if (Double.parseDouble(yu_e) > 0) {
						yue_selectBtn.setSelected(true);
						yue_selectBtn.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View v) {
								// TODO Auto-generated method stub
								if (isYe) {
									yue_selectBtn.setSelected(false);
									yue_selectBtn
											.setBackgroundResource(R.drawable.zhifu_unselected);
								} else {
									yue_selectBtn.setSelected(true);
									yue_selectBtn
											.setBackgroundResource(R.drawable.zhifu_selected);
								}
								isYe = !isYe;

							}
						});
					}

					else {
						yue_selectBtn.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View v) {
								// TODO Auto-generated method stub
								ByAlert.alert("没有可用余额");
							}
						});
						yue_selectBtn.setSelected(false);
						// yue_selectBtn.setEnabled(false);
					}
					zhifubao_selectBtn.setEnabled(true);
					zhifubao_selectBtn.setSelected(true);
					isZFB = true;
					isWX = false;
					wx_selectBtn.setEnabled(true);
					wx_selectBtn
							.setBackgroundResource(R.drawable.zhifu_unselected);
					zhifubao_selectBtn
							.setBackgroundResource(R.drawable.zhifu_selected);
				}

				// finish();
			}
		}
	}

	private void wxPay(BuyBean bean) {
		// TODO Auto-generated method stub
		mainPresenter.wxPay(bean.getPayInfo().getCode(), bean.getPayInfo()
				.getTotalPrice(), bean.getPayInfo().getDesc());
	}
}
